<?php

class CategoryTable extends Doctrine_Table
{
    public function getCategoriesByParent($menu = null,$parent_id = null, $visible = true )
    {
        $query = Doctrine_Query::create()->from('Category');
        if(isset($menu))
        {
            $query->addWhere('menu = ?', $menu);
            if (isset($parent_id))
                $query->andWhere('parent = ?', $parent_id);
        }
        elseif (isset($parent_id))
             $query->addWhere('parent = ?', $parent_id);
        else
             $query->addWhere('parent is null');
        if($visible)
            $query->andWhere('visible = ?' , $visible);
        $query->addOrderBy('menu asc, ord asc, id asc');
        return $query->execute();
    }

    public function getCategoriesCascade($menu = null, $category_id = null, $visible = false)
    {
        $categories = $this->getCategoriesByParent($menu, $category_id, $visible);
        $result = array();
        if ($categories->count() > 0)
        {
            foreach($categories as $category)
                $this->addCategoryRecursive($result, $category, $visible);
        }
        return $result;
    }

    private function addCategoryRecursive(&$result,  $category, $visible)
    {
        $pomresult['category'] = $category;
        $pomresult['children'] = array();
        $categories = $this->getCategoriesByParent($category->getMenu(), $category->getId(), $visible);
        if ($categories->count()>0)
        {
            foreach($categories as $subcategory) 
                $this->addCategoryRecursive($pomresult['children'], $subcategory, $visible);
        }
        $result[] = $pomresult;
    }

    public function getCategoriesCascadeFlat($menu = null, $category_id = null, $visible = false, $exclude = null)
    {
        $categories = $this->getCategoriesByParent($menu, $category_id, $visible);
        $result = array();
        if ($categories->count()>0)
        {
            foreach($categories as $category)
                $this->addCategoryRecursiveFlat($result, $category, $visible, 0, $exclude);
        }
        return $result;
    }

    private function addCategoryRecursiveFlat(&$result,  $category, $visible, $level, $exclude)
    {
        if ($category->getId() != $exclude)
        {
            $pomresult['category'] = $category;
            $pomresult['level'] = $level;
            $result[] = $pomresult;
            $categories = $this->getCategoriesByParent($category->getMenu(), $category->getId(), $visible);
            if ($categories->count()>0)
            {
                foreach($categories as $subcategory)
                    $this->addCategoryRecursiveFlat($result, $subcategory, $visible, $level+1, $exclude);
            }
        }
    }
}
